from flask import Blueprint, request, jsonify, current_app
from neo4j.graph import Node
from app.utils.response_util import ResponseUtil
from app.utils.mysql_util import MySQLUtil

bp = Blueprint('query', __name__, url_prefix='/api')  # 修改路由前缀

@bp.route('', methods=['GET'])  # 修改为支持 GET 请求
def query_neo4j():
    """执行自定义 Neo4j 查询"""
    try:
        query = request.args.get('query')  # 从 URL 参数获取查询语句
        
        if not query:
            return ResponseUtil.missing_params("缺少查询语句")

        with current_app.neo4j_driver.session() as session:
            result = session.run(query)
            records = []
            for record in result:
                record_dict = {
                    key: dict(value) if isinstance(value, Node) else value 
                    for key, value in record.items()
                }
                records.append(record_dict)

        return ResponseUtil.success(data=records)
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/data/<query_type>', methods=['GET'])
def get_relationship_data(query_type):
    """获取不同类型的关系数据"""
    try:
        limit = request.args.get('limit', type=int, default=0)
        
        # 如果是文物-器型关系或文物-纹样关系，使用MySQL查询
        if query_type in ['artifact-qixing', 'artifact-pattern']:
            mysql_util = MySQLUtil()
            
            if query_type == 'artifact-qixing':
                query = """
                    SELECT qixing, artifact_name 
                    FROM artifact_main_structure 
                    WHERE qixing IS NOT NULL 
                    GROUP BY qixing, artifact_name
                """
            else:  # artifact-pattern
                query = """
                    SELECT 
                        ams.artifact_code AS artifact_id,
                        ams.artifact_name,
                        ams.period,
                        apg.纹样名称 AS pattern_name,
                        apg.含义解读 AS pattern_meaning,
                        apg.pattern_type,
                        apg.算法提取纹样图sam AS pattern_image_sam,
                        apg.手工绘制的纹样原图 AS pattern_image_manual
                    FROM 
                        artifact_main_structure ams
                    JOIN 
                        artifact_pattern_gene apg
                    ON 
                        ams.artifact_code = apg.artifact_code
                    WHERE 
                        ams.artifact_name IS NOT NULL 
                        AND apg.纹样名称 IS NOT NULL
                """
            
            if limit > 0:
                query += f" LIMIT {limit}"
                
            results = mysql_util.get_all(query)
            
            # 转换为图数据格式
            nodes = []
            links = []
            node_map = {}
            
            if query_type == 'artifact-qixing':
                for row in results:
                    # 添加文物节点
                    if row['artifact_name'] not in node_map:
                        nodes.append({
                            'id': row['artifact_name'],
                            'name': row['artifact_name'],
                            'type': 'artifact'
                        })
                        node_map[row['artifact_name']] = True
                    
                    # 添加器型节点
                    if row['qixing'] not in node_map:
                        nodes.append({
                            'id': row['qixing'],
                            'name': row['qixing'],
                            'type': 'qixing'
                        })
                        node_map[row['qixing']] = True
                    
                    # 添加关系
                    links.append({
                        'source': row['artifact_name'],
                        'target': row['qixing'],
                        'type': 'has_qixing'
                    })
            else:  # artifact-pattern
                for row in results:
                    artifact_id = str(row['artifact_id'])  # 确保ID是字符串
                    pattern_name = str(row['pattern_name'])  # 确保纹样名称是字符串
                    
                    # 添加文物节点
                    if artifact_id not in node_map:
                        nodes.append({
                            'id': artifact_id,
                            'name': row['artifact_name'],
                            'type': 'artifact',
                            'period': row['period']
                        })
                        node_map[artifact_id] = True
                    
                    # 添加纹样节点
                    pattern_id = f"pattern_{pattern_name}_{artifact_id}"  # 使用文物ID确保唯一性
                    if pattern_id not in node_map:
                        nodes.append({
                            'id': pattern_id,
                            'name': pattern_name,
                            'type': 'pattern',
                            'pattern_type': row['pattern_type'],
                            'pattern_meaning': row['pattern_meaning'],
                            'pattern_image_sam': row['pattern_image_sam'],
                            'pattern_image_manual': row['pattern_image_manual'],
                            'artifact_id': artifact_id  # 添加关联的文物ID
                        })
                        node_map[pattern_id] = True
                    
                    # 添加关系
                    links.append({
                        'source': artifact_id,
                        'target': pattern_id,
                        'type': 'has_pattern'
                    })
            
            # 打印调试信息
            print("Nodes:", nodes)
            print("Links:", links)
            
            return ResponseUtil.success(data={'nodes': nodes, 'links': links})
            
        # 其他关系类型使用Neo4j查询
        with current_app.neo4j_driver.session() as session:
            if query_type == 'artifact-meaning':
                # 获取文物-含义关系
                query = """
                    MATCH (a:CulturalItem)-[r]-(m:Meaning)
                    RETURN a, r, m
                """
                if limit > 0:
                    query += f" LIMIT {limit}"
                result = session.run(query)
            elif query_type == 'artifact-story':
                # 获取文物-故事关系
                query = """
                    MATCH (a:CulturalItem)-[r]-(s:Story)
                    WHERE s.story IS NOT NULL
                    RETURN a, r, s
                """
                if limit > 0:
                    query += f" LIMIT {limit}"
                result = session.run(query)
            elif query_type == 'artifact-all':
                # 获取文物的所有关系（两层）
                query = """
                    MATCH (a:CulturalItem)
                    OPTIONAL MATCH (a)-[r1]-(n1)
                    OPTIONAL MATCH (n1)-[r2]-(n2)
                    WHERE n2 <> a AND NOT n2:CulturalItem
                    RETURN a, r1, n1, r2, n2
                """
                if limit > 0:
                    query += f" LIMIT {limit}"
                result = session.run(query)
            else:
                return ResponseUtil.error("不支持的查询类型")

            nodes, links = [], []
            seen_nodes = set()

            for record in result:
                source_node = record['a']
                # 处理第一层关系
                if 'r1' in record and record['r1'] is not None:
                    target_node = record['n1']
                    # 添加源节点
                    if source_node.element_id not in seen_nodes:
                        nodes.append({
                            'element_id': source_node.element_id,
                            'labels': list(source_node.labels),
                            'properties': dict(source_node)
                        })
                        seen_nodes.add(source_node.element_id)

                    # 添加第一层目标节点
                    if target_node.element_id not in seen_nodes:
                        nodes.append({
                            'element_id': target_node.element_id,
                            'labels': list(target_node.labels),
                            'properties': dict(target_node)
                        })
                        seen_nodes.add(target_node.element_id)

                    # 添加第一层关系
                    links.append({
                        'source': source_node.element_id,
                        'target': target_node.element_id,
                        'type': type(record['r1']).__name__
                    })

                    # 处理第二层关系
                    if 'r2' in record and record['r2'] is not None and 'n2' in record and record['n2'] is not None:
                        second_target = record['n2']
                        # 添加第二层目标节点
                        if second_target.element_id not in seen_nodes:
                            nodes.append({
                                'element_id': second_target.element_id,
                                'labels': list(second_target.labels),
                                'properties': dict(second_target)
                            })
                            seen_nodes.add(second_target.element_id)

                        # 添加第二层关系
                        links.append({
                            'source': target_node.element_id,
                            'target': second_target.element_id,
                            'type': type(record['r2']).__name__
                        })
                else:
                    # 处理普通关系（文物-意义或文物-故事）
                    target_node = record['m' if query_type == 'artifact-meaning' else 's']
                    # 添加源节点
                    if source_node.element_id not in seen_nodes:
                        nodes.append({
                            'element_id': source_node.element_id,
                            'labels': list(source_node.labels),
                            'properties': dict(source_node)
                        })
                        seen_nodes.add(source_node.element_id)

                    # 添加目标节点
                    if target_node.element_id not in seen_nodes:
                        nodes.append({
                            'element_id': target_node.element_id,
                            'labels': list(target_node.labels),
                            'properties': dict(target_node)
                        })
                        seen_nodes.add(target_node.element_id)

                    # 添加关系
                    links.append({
                        'source': source_node.element_id,
                        'target': target_node.element_id,
                        'type': type(record['r']).__name__
                    })

            return ResponseUtil.success(data={'nodes': nodes, 'links': links})

    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/search', methods=['GET'])
def search_items():
    """搜索文物"""
    try:
        name = request.args.get('name')
        
        if not name:
            return ResponseUtil.missing_params("缺少搜索关键词")

        with current_app.neo4j_driver.session() as session:
            # 使用模糊匹配搜索文物
            result = session.run("""
                MATCH (n:CulturalItem)
                WHERE n.name CONTAINS $name
                RETURN n
            """, name=name)
            
            items = []
            for record in result:
                node = record['n']
                items.append({
                    'element_id': node.element_id,
                    'labels': list(node.labels),
                    'properties': dict(node)
                })

            return ResponseUtil.success(data=items)
    except Exception as e:
        return ResponseUtil.error(str(e))